package io.renren.core.interceptor;

import cn.hutool.json.JSONUtil;
import io.renren.core.config.ProjectConStant;
import io.renren.utils.ClientSignatureUtil;
import io.renren.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Slf4j
@Component
public class OuterInterfaceAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String id = request.getParameter("id");
        String timestamp = request.getParameter("timestamp");
        String sign = request.getParameter("sign");

        if (StringUtils.isBlank(id) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(sign) || !Objects.equals(id, ProjectConStant.OUTER_INTERFACE_APP_ID)) {
            responseResult(response, R.error(1004, "参数错误"));
            return false;
        }

        Boolean flag = ClientSignatureUtil.checkSign(id, Integer.parseInt(timestamp), sign);

        if (flag) {
            return true;
        }

        responseResult(response, R.error(1001, "签名错误"));
        return false;
    }

    private void responseResult(HttpServletResponse response, R result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSONUtil.toJsonStr(result));
        } catch (IOException ex) {
            log.error("拦截器响应异常================>" + ex.getMessage());
        }
    }
}
